/*!
 * New Launch.
 * Date: 2015/12/29.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
    'jquery',
		'pageInit',
		'formValidator',
    'formAjax',
    'notification',
    'select2',
    'holder',
    'uploadFiles'
	], function ($, vamakerPage, formValidator, formAjax, VamOpMsg, select2, holder, UploadFiles) {
  // New Creative Template Form.
  $(function () {
    var $dataFrm = $('#data-frm'),
        $submitBtn = $dataFrm.find('button[type="submit"]'),
        dataFieldRule, options, dataValidator;
      // console.log($dataFrm);
      dataFieldRule = {
        creative_template_name:{
          rule:{
              required:{
                  message:VAM.j('Creative template name be empty')
              }
          },
          messageContainer:'creative_template_name_err'
        },
        crowd_tag:{
          rule:{
              required:{
                message:VAM.j('The crowd label cannot be empty')
              }
          },
          messageContainer:'crowd_tag_err'
        },
        logo_click_url:{
          rule:{
              required:{
                message:VAM.j('Logo click Url cannot be empty')
              },
              url:{
                message:VAM.j('Please input correct Url (starting with http:// or https://)')
              }
          },
          messageContainer:'logo_click_url_err'
        },
        backup_click_url:{
          rule:{
              required:{
                message:VAM.j('Render click URL cannot be empty')
              },
              url:{
                message:VAM.j('Please input correct Url (starting with http:// or https://)')
              }
          },
          messageContainer:'backup_click_url_err'
        },
        upload_logo: {
          rule: {
            required: {
              message: VAM.j('Upload Logo material cannot be empty')
            }
          },
          messageContainer: 'upload_logo_err'
        },
        upload_backup: {
          rule: {
            required: {
              message: VAM.j('Upload render material cannot be empty')
            }
          },
          messageContainer: 'upload_backup_err'
        }
      };
      options = {
        submitOnSucceed: false,
        onvalidate: function(evt) {
          if (evt.resultList.length <= 0) {
              $dataFrm.ajaxSubmit({
                  beforeSubmit: function() {
                    $submitBtn.button('loading');
                  },
                  success: function (data) {
                    $submitBtn.button('reset');
                    if (data.status === 'success') {
                      VAM.fn.Messenger(data.msg, 'success');
                      window.location.href = 'index';
                    } else {
                      VAM.fn.Messenger(data.reason, 'error');
                    }
                  }
              });
          };
        }
      };
      formValidator.validate($dataFrm, dataFieldRule, options);
      dataValidator = formValidator.dataValidator;
      dataValidator.addRule('effectiveNumber',function(val, opt){
        return !!(val && /^\d+(\.\d{1,2})?$/.test(val));
      });
  });
  // Upload file.
  $(function () {
      'use strict';
      var url = VAM.getVar('UPLOAD_MATERIAL_URL'),
          $fileUpload = $('#fileupload'),
          $progressBar = $('#progress .progress-bar'),
          $table = $('#files').find('table tbody');
      $fileUpload.fileupload({
        url: url,
        dataType: 'json',
        done: function (e, data) {
          if (data.result.status === 'success') {
            var materialData = data.result.data,
             list = materialData['table'],
             listStr = '';
            console.log(materialData);
            VAM.fn.Messenger(data.result.msg, 'success');
            listStr = '<tr>'
                    + '<td>' + list.id + '</td>'
                    + '<td>' + list.name + '</td>'
                    + '<td>' + list.size + '</td>'
                    + '<td>' + list.last_update + '</td>'
                    + '<td>' + list.judgeInfo + '</td>'
                    + '<td>' + list.upload_by + '</td>'
                    + '</tr>';
            $table.append(listStr);
            $('#upload-confirm-operate').data('materialId', list.id).data('materialInfo', materialData['preview']);
          }else {
            VAM.fn.Messenger(data.result.reason, 'error');
            $('#upload-confirm-operate').data('materialId', '');
          };
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $progressBar.css('width','0%').text('0%');
            $progressBar.css(
                'width',
                progress + '%'
            ).text(progress + '%');
        }
      })
      .prop('disabled', !$.support.fileInput)
      .parent().addClass($.support.fileInput ? undefined : 'disabled');
  });
  // Init Creative Template Upload.
  $(function () {
    var $uploadOperateBtn = $('.upload-operate-btn'),
      $uploadMaterialModal = $('#upload-material-modal'),
      $uploadMaterialOperate = $('#upload-confirm-operate');

      $uploadMaterialModal.on('hidden.bs.modal', function (evt) {
        var $me = $(this);
        $('#progress .progress-bar').css('width','0%').text('0%');
        $('#files').find('tbody').html('');
      });

      $uploadOperateBtn.on('click', function (evt) {
        var $me = $(this),
          operateType = $me.data('type');
        $uploadMaterialOperate.data('type', operateType);
        $uploadMaterialModal.modal('show');
      });

      $uploadMaterialOperate.on('click', function(evt) {
        var $me = $(this),
          type = $me.data('type'),
          $uploadMaterialErr = $('#upload_' + type + '_err'),
          $uploadMaterialInput = $('#upload_' + type),
          materialId = $me.data('materialId'),
          prevewInfo = $me.data('materialInfo');
        evt.preventDefault();
        console.log(type);
        // console.log(materialId);
        // console.log(prevewInfo);
        if (materialId !== '') {
          $uploadMaterialInput.val(materialId);
          $uploadMaterialModal.modal('hide');
          $uploadMaterialErr.find('em').text('');
          // TODO: creative material preview.
          VAM.fn.creativeMaterialPreview($('.creative-preview'), prevewInfo);
        } else {
          $uploadMaterialInput.val('');
        };
      });
  });
});
